import extend from 'dva-model-extend';
import settings from '@/settings';
import model from '@/baseModel';
import { getOne, getList, check, lock, unlock, deleteRows } from '@/services/user';
import { getAll as getAllRoles } from '@/services/role';
import { getNodes } from '@/services/group';

const { pagination } = settings;

const initState = {
  valid: true,
  groups: [], // 部门
  roles: [], // 角色
  roleIds: [], // 已选择角色
  groupIds: [], // 勾选的部门
  groupPaths: [] // 勾选部门的path
};

export default extend(model, {
  namespace: 'user',
  state: {
    ...initState
  },
  effects: {
    *reset(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          data: undefined,
          ...initState
        },
      });
    },
    *fetchOne({ payload }, { call, put }) {
      const { data = {} } = yield call(getOne, payload);
      const { roles = [], group, ...rest } = data;
      yield put({
        type: 'updateState',
        payload: {
          data: rest,
          roleIds: roles,
          groupIds: group ? [group] : []
        },
      });
    },
    *fetchList({ payload = pagination }, { call, put }) {
      const { data } = yield call(getList, payload);
      yield put({
        type: 'updateState',
        payload: {
          list: data,
          params: payload,
        },
      });
    },
    *delete({ payload }, { call, put }) {
      yield call(deleteRows, payload);
    },
    *lock({ payload }, { call, put }) {
      yield call(lock, payload);
    },
    *unlock({ payload }, { call, put }) {
      yield call(unlock, payload);
    },
    *valid({ payload }, { call, put }) {
      const { valid } = yield call(check, payload);

      yield put({
        type: 'updateState',
        payload: {
          valid,
        },
      });
    },
    *fetchRoles({ payload }, { call, put }) {
      const { data } = yield call(getAllRoles, payload);
      yield put({
        type: 'updateState',
        payload: {
          roles: data,
        },
      });
    },
    *fetchGroups({ payload }, { call, put }) {
      const { data } = yield call(getNodes, payload);
      yield put({
        type: 'updateState',
        payload: {
          groups: data,
        },
      });
    },
  },
});
